﻿using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DiffuseEnjoyIdle.Core.Attributes
{
    /// <summary>
    /// 自定义Swagger隐藏过滤器
    /// </summary>
    public class HiddenFieldFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            if (context.DocumentName == "v1")
                return;
            foreach (ApiDescription apiDescription in context.ApiDescriptions)
            {
 
                if (apiDescription.TryGetMethodInfo(out MethodInfo methodInfo))
                {
                    if (methodInfo.CustomAttributes.Any(a=>a.AttributeType== typeof(HiddenFieldAttribute))
                        ||methodInfo.ReflectedType.CustomAttributes.Any(a=>a.AttributeType== typeof(HiddenFieldAttribute)))
                    {
                        string key = "/" + apiDescription.RelativePath; 
                        swaggerDoc.Paths.Remove(key);
                        continue;
                    }
                }
                foreach (var item in apiDescription.ParameterDescriptions)
                {
                    var find = item.Type;
                    var name = find.GetProperties().Where(a => Attribute.IsDefined(a, typeof(HiddenFieldAttribute))).Select(a => a.Name.ToLower());
                    if (!name.Any())  continue;

                    foreach (var sch in swaggerDoc.Components.Schemas.Where(a => a.Key == find.Name).Select(a => a.Value))
                    {
                        var key = sch.Properties.Where(a => name.Contains(a.Key.ToLower()));
                        foreach (var kes in key)
                        { 
                          sch.Properties.Remove(kes);
                        }
                    } 
                } 
            }
        }
    }
}
